package com.shop.controller;

import com.shop.dao.OrderDao;
import com.shop.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderDao orderDao;

    @PostMapping("/add")
    public ResponseEntity<Map<String, String>> addOrder(@RequestParam int userId, @RequestParam String amount, @RequestParam int merchantId, @RequestParam int productId) {
        Order order = new Order(userId, amount, merchantId, productId);
        int result = orderDao.insertOrder(order);
        if (result > 0) {
            Map<String, String> response = new HashMap<>();
            response.put("下单成功", "状态：" + order.getStatus());
            return ResponseEntity.ok(response);
        } else {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("下单失败", "订单创建失败");
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @GetMapping("/user/{userId}")
    public Map<String, Object> getUserOrders(@PathVariable String userId) {
        List<Order> orders = orderDao.selectOrderByUserId(userId);
        Map<String, Object> response = new HashMap<>();
        response.put("orders", orders);
        return response;
    }

    @GetMapping("/Merchant/{merchantId}")
    public Map<String, Object> getMerchantIdOrders(@PathVariable String merchantId) {
        List<Order> orders = orderDao.selectOrderByMerchantId(merchantId);
        Map<String, Object> response = new HashMap<>();
        response.put("orders", orders);
        return response;
    }

    @PutMapping("/update/{orderId}")
    public ResponseEntity<Map<String, String>> updateOrderStatus(@PathVariable String orderId,
                                                                 @RequestParam String status) {
        int result = orderDao.updateOrderStatus(orderId, status);
        if (result > 0) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "订单状态更新成功");
            response.put("status", "success"); // 添加 status 字段
            return ResponseEntity.ok(response);
        } else {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "订单未找到或更新失败");
            errorResponse.put("status", "error"); // 添加 status 字段
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);
        }
    }

}